package org.example;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class File_Demo7 {
    public static void main(String[] args) {
        File file = new File("路径");
        HashMap <String,Integer> hm= getCount(file);
        System.out.println(hm);
    }
    public static HashMap getCount(File file){
        //键 ：文件名
        //值 ：文件出现的次数
        HashMap<String, Integer> hm = new HashMap<>();
        //进入目录存入数组
        File[] file1 = file.listFiles();
        //遍历数组
        for (File file2 : file1) {
            //判断是否是文件
            if(file2.isFile()){
                String name = file2.getName();
                //以点切分
                String[]arr=name.split("\\.");
                if(arr.length>=2){
                   String endname=arr[arr.length-1];
                    if(hm.containsKey(endname)){
                        int count=hm.get(endname);
                        count++;
                        hm.put(endname,count);
                    }else{
                        hm.put(endname,1);
                    }
                }
            }else{
                //子文件夹
                HashMap <String,Integer> sonMap = getCount(file2);
                Set<Map.Entry<String, Integer>> entries = sonMap.entrySet();
                for (Map.Entry<String, Integer> entry : entries) {
                   if(hm.containsKey(entry.getKey())){
                       //存在
                       int count=hm.get(entry.getKey());
                       count=count+entry.getValue();
                   }else{
                       //不存在
                       hm.put(entry.getKey(),entry.getValue());
                   }
                }
            }
        }
        return hm;
    }
}
